<?php
/*
 * @file			weibo.class.php
 * @CopyRight		(C)1996-2099 SINA Inc.
 * @Project			Xweibo
 * @Author			heli <heli1@staff.sina.com.cn>
 * @Create Date:	2010-07-08
 * @Modified By:	heli/2010-11-15
 * @Brief			微博api操作类
 */
require_once 'config.inc.php';
require_once 'qq_oauth.class.php';

 class qqWeibo_class
 {

	var $http;
	var $token;
	var $shal_method;
	var $consumer;
	var $format = 'json';

	/**
	 * 构造函数
	 * @param $oauth_token
	 * @param $oauth_token_secret
	 * @return
	 */
	function __construct($app_key = NULL, $secret_key = NULL)
	{
		if(!$app_key) {
			$app_key = qqApiConfig::$APIKey;
			$secret_key=qqApiConfig::$SecretKey;
		}
		
        $this->sha1_method = new OAuthSignatureMethod_HMAC_SHA1();
        $this->consumer = new OAuthConsumer($app_key, $secret_key);	
		$this->http = vApi::getHttp();
	}

	/**
	 * 设置access_token
	 * @return
	 */
	function setToken($oauth_token, $oauth_token_secret)
	{
		$this->token = new OAuthConsumer($oauth_token, $oauth_token_secret);
	}	


  //************************************* oauth ***************************************************/	
    /**
     * 第一步获取request token
	 * @param string $oauth_callback	回调地址
     * @return array a key/value array containing oauth_token and oauth_token_secret
     */
    function getRequestToken($oauth_callback)
	{
        $parameters = array();
        $parameters['oauth_callback'] = $oauth_callback;

		$this->token = null;
        $request = $this->oAuthRequest(qqApiConfig::$url.'oauth/qzoneoauth_request_token', 'GET', $parameters, false, true);
        $token = QQ_OAuthUtil::parse_parameters($request);
        $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
        return $token;
    }

   /**
     * 第二步：获取url
	 * @param array|string $token
	 * @param bool $sign_in_with_Weibo
	 * @param string $url
     * @return string
     */
    function getAuthorizeURL($token, $callback, $display='')
	{
        if (is_array($token)) {
            $token = $token['oauth_token'];
        }
       
        $callback = urlencode($callback);
        $wap 	  = 'mobile'==$display ? 'wap=2' : 'mini=1';
        return qqApiConfig::$url.'oauth/qzoneoauth_authorize?oauth_consumer_key='.qqApiConfig::$APIKey.'&oauth_token='.$token."&$wap&oauth_callback=$callback"; 
    }

    /**
	 * 第三步：获取access_token
	 * @param string $oauth_vericode
	 * @param array $oauth_token
     * @return array array("oauth_token" => the access token,
     *                "oauth_token_secret" => the access secret)
     */
    function getAccessToken($auth_token, $oauth_vericode=FALSE)
	{
        $parameters 				  = array();
        $parameters['oauth_vericode'] = $oauth_vericode;
        

		$this->token = new OAuthConsumer($auth_token['oauth_token'], $auth_token['oauth_token_secret']);
        $request 	 = $this->oAuthRequest(qqApiConfig::$url.'oauth/qzoneoauth_access_token', 'GET', $parameters, false, true);
		if (!$request || (is_array($request) && !empty($request['errno']))) {
			return $request;
		}
		
        $token = QQ_OAuthUtil::parse_parameters($request);
        $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
        return $token;
    }
	
    
	function throwException($result)
	{
		$msg   = array();
		$error = json_decode($result, true);
		switch ($error['errcode']) 
		{
			case '-111':
				$msg = array(
					'error_code' => '1040107',
					'error' => $error['errcode'].':'.$error['msg']
				);
			break;
					
			default:
				$msg = array(
					'error_code' => '1050000',
					'error' => 'unknow system error  api: ' . $error['errcode'].':'.$error['msg']
				);					
		}
		return $msg;
	}

    /**
     * Format and sign an OAuth / API request
	 * @param string $url
	 * @param string $method
	 * @param array $parameters
	 * @param bool $multi
     * @return array
     */
    function oAuthRequest($url, $method, $parameters, $multi = false, $userType = false)
	{
        $request = QQ_OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $parameters);
        $request->sign_request($this->sha1_method, $this->consumer, $this->token);
		$method = strtoupper($method);
        switch ($method) {
	        case 'GET':
				$this->http->base_string = $request->base_string;
				$this->http->key_string = $request->key_string;
				$this->http->setUrl($request->to_url());
				$result = $this->http->request();
				break;

			case 'DELETE':
				$this->http->base_string = $request->base_string;
				$this->http->key_string = $request->key_string;
				$this->http->setUrl($request->get_normalized_http_url());
				$this->http->setData($request->to_postdata($multi));
				$result = $this->http->request('delete');
				break;

	        default:
				$this->http->base_string = $request->base_string;
				$this->http->key_string = $request->key_string;
				$this->http->setUrl($url);
				$this->http->setData($request->to_postdata($multi));
				if ($multi) {
					$header_array2 = array("Content-Type: multipart/form-data; boundary=" . $GLOBALS['___qqwbStData']['boundary'] , "Expect: ");				
					$config = array('http_header' => $header_array2);
					$this->http->setConfig($config);
				}

				$result = $this->http->request('post');
        }
        //-------------------------------------------------------------
        //　发完了API请求
        $code = $this->http->getState();
		if (is_array($result) && isset($result['errcode'])) {
			return $this->throwException($result);
		}
        
		if (200 != $code) {
			//日志处理
			if (0 == $code) {
				$msg = array(
					'error_code' => '1040002',
					'error' => '系统繁忙，请稍后再试'
				);
				return $msg;
			}	
					
			$db = vApi::DB();
			$logParam = array('url'=>$url, 'post_data'=>json_encode($parameters), 'http_code'=>$code, 'result'=>$result, 'curl_error'=>$this->http->getError(), 'service_id'=>2, 's_ip'=>$_SERVER['SERVER_ADDR'], 'app_source'=>vApi::source(), 'uid'=>vApi::uid(), 'log_time'=>date('Y-m-d H:i:s'));
			$db->save($logParam, null, API_TB_3RD_API_LOG);
			unset($db);				
			return $this->throwException($result);
		}		
		
		if ($userType === true) {
			return $result;
		}

		$result = json_decode(preg_replace('#(?<=[,\{\[])\s*("\w+"):(\d{6,})(?=\s*[,\]\}])#si', '${1}:"${2}"', $result), true);
		return $result;
    }

    
	/*
	 * 获取用户信息
	 */
	function getUserInfo($params)
	{
		$url = qqApiConfig::$url.'user/get_user_info';
		$params['format'] = $this->format;
		
		return $this->oAuthRequest($url, 'get', $params);
	}
	
 }